import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  setToken
} from '@/utils/publicUtils/auth'

// 路由加密解密
const CryptoJS = require('crypto-js') // 引用AES源码js
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// import {
//  objCopy
// } from '@/utils'
// create an axios instance
// const service = axios.create({
//   withCredentials: true, // send cookies when cross-domain requests
//   timeout: 50000 // request timeout
// })
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: "/dist/",
  // 超时
  timeout: ''
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['x-auth-token'] = getToken()
      config.headers['Content-Type'] = 'application/json'
    }
    config.async = false
    // 加密
    var strParams = config.params ? config.params.toString() : ''
    const md5Hash = CryptoJS.MD5(strParams).toString()
    config.headers['sign'] = md5Hash

    // 对参数做格式转换
    // var data = typeof config.data === 'object' ? objCopy(config.data) : {}
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        const part = encodeURIComponent(propName) + '='
        if (value !== null && typeof (value) !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              const params = propName + '[' + key + ']'
              const subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    // if (config.method.toUpperCase() === 'PUT') {
    //   config.method = 'POST'
    //   config.headers['X-HTTP-Method-Override'] = 'PUT'
    // }
    // if (config.method.toUpperCase() === 'DELETE') {
    //   config.method = 'GET'
    //   config.headers['X-HTTP-Method-Override'] = 'DELETE'
    // }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

  /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
  response => {
    // 每次请求更新token
    const token = response.headers['x-auth-token'] ? response.headers['x-auth-token'] : ''
    if (token !== '') {
      setToken(token)
      store.dispatch('user/getInfo')
    }
    const res = response.data
    // if( getToken()!=undefined&&getToken()!=null&&getToken()!=''){
    if (res === '') {
      return Promise.reject(new Error(res.msg || '出错'))
      // }
    }


    if(res.repCode){
      // res.repCode 图片滑块验证
      if(res.repCode === '0000'){
        return res
      } else {
        Message({
          message: res.repMsg || '出错',
          type: 'error'
        })
      }
    } else {
      // 其他 api
      if (res.code === 9000 || res.code === 200 || res.code === 20000) {
        return res
      } else {
        switch (res.code) {
          case 9004:
            if (!store.getters.isExpireToken) {
              store.dispatch('user/setExpireToken')
              Message({
                message: '登录过期，请重新登录',
                type: 'warning',
                duration: 5 * 1000
              })
              setTimeout(() => {
                store.dispatch('user/resetToken').then(() => {
                  location.reload()
                })
              }, 1000)
            }
            break
          case 405:
            Message({
              message: '请勿频繁操作',
              type: 'warning',
              duration: 5 * 1000
            })
            break
          default:
            //  if( getToken()!=undefined&&getToken()!=null&&getToken()!=''){
            Message({
              message: res.msg || '出错',
              type: 'error'
            })
            return Promise.reject(res.msg || '出错')
            //  }
        }
      }
    }
  }
  // error => {
  //  Message({
  //    message: '网络出错，请联系管理员',
  //    type: 'error',
  //    duration: 5 * 1000
  //  })
  //  return Promise.reject('网络出错，请联系管理员')
  // }
)
export default service
